package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.TravelComment;
import cn.wolfcode.luowowo.query.TravelCommentQuery;
import cn.wolfcode.luowowo.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional //事务最后处理
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public TravelComment get(String id) {
        Optional<TravelComment> optional = repository.findById(id);
        if (optional != null) {
            return optional.get();
        }
        return null;
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {
        Query query = new Query();
        //分页
        if (StringUtils.hasLength(qo.getTravelId())) {
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        ;
        return DBHelper.query(template, TravelComment.class, query, qo.getPageable());
    }

    //在攻略中添加评论
    @Override
    public void addComment(TravelComment comment) {

        //查询评论数据
        String refId = comment.getRefComment().getId();
        if (StringUtils.hasLength(refId)) {
            //不是第一层
            //设置引入评论
            TravelComment refComment = this.get(refId);
            comment.setRefComment(refComment);
        }
        //保存进mongodb
        repository.save(comment);
    }

    //攻略里的评论点赞
    @Override
    public void commentThumb(String cid, String uid) {
       /* //1.判断用户是点赞还是取消点赞
        //获取存点赞用户的 id 集合 list
        TravelComment comment = this.get(cid);//评论是存在mongodb中的
        List<String> userList = comment.getThumbuplist();//从评论中拿到存用户id的list

        if (!userList.contains(uid)) {
            //2.不包含，点赞，list中存当前用户的id
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            userList.add(uid);

        }else {
            //3.包含，取消点赞，list中移除当前用户的id
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            userList.remove(uid);
        }*/
        //4.将list改变的数据同步到mongodb中,更新
        // repository.save(comment);
    }
}
